<?php
/**
 * 后台管理员登录
 */
defined('BASEPATH') OR exit("No direct script access allowed");

class Patient extends CI_Controller{


	//构造初始化函数
	public function __construct(){
		parent::__construct();

		//加载数据库
		$this->load->database();

		//加载admin模型
		$this->load->model('admin/Patient_model','patient');
		$this->load->model('admin/LogAll_model','logAll');

		//加载表单验证规则
		$this->load->library('form_validation');

		$this->checkLogStatus();
		date_default_timezone_set("PRC");
	}


	/*
	 * 检查登陆状态
	 */
	public function checkLogStatus()
	{
		if (!$this->session->userdata('doctorName')){
			redirect('doctor/Login');
		}
	}

	//医生列表详细信息
	public function index()
	{
		$doctorid=$this->session->userdata('doctorId');
		// //获取所有信息
	    $data['dataDoctor']=$this->patient->getAll2($doctorid);
	    $this->testexcel($data['dataDoctor']);
		$this->load->view("admin/Patient.html",$data);
	}

	public function upload(){

		if(is_uploaded_file($_FILES['upload_file1']['tmp_name'])){

						$first_file = $_FILES['upload_file1'];  //获取文件1的信息

						if ($first_file['error'] == UPLOAD_ERR_OK){

					    $temp_name = $first_file['tmp_name'];

					    $file_name = $first_file['name'];

					    $type=$first_file["type"];//上传文件的类型

					  	if($type!="application/vnd.ms-excel")
					  	{
					  		 $a=base_url("assets/error/pscsb.html");
					    	 header("Location: $a"); 
					  		exit();
					  	}

					  	//文件时间戳
					  	$timecuo=time();
					    //移动临时文件夹中的文件1到存放上传文件的目录，并重命名为真实名称
					    $aa="./assets/upload/".$timecuo.$file_name;
					    // echo base_url();
						move_uploaded_file($temp_name, $aa);
					    
						//开始分析xls
						require "assets/PHPExcel/PHPExcel.php";

					    require 'assets/PHPExcel/PHPExcel/IOFactory.php';

					    require 'assets/PHPExcel/PHPExcel/Reader/Excel5.php';

					    $objReader = PHPExcel_IOFactory::createReader('Excel5'); //use Excel5 for 2003 format 

					    $excelpath=$aa;

					    $objPHPExcel = $objReader->load($excelpath); 

					    $sheet = $objPHPExcel->getSheet(0); 

					    $highestRow = $sheet->getHighestRow();           //取得总行数 

						$highestColumn = "F"; //取得总列数
						$count=0;
					    for($j=3;$j<=$highestRow;$j++)                        //从第二行开始读取数据
					  	 { 
					  	 		$count++;
							    $str="";

						        for($k='A';$k<=$highestColumn;$k++)            //从A列读取数据

						         { 

						             $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'|*|';//读取单元格

						         } 

								$str=mb_convert_encoding($str,'utf-8','auto');//根据自己编码修改

								$strs = explode("|*|",$str);
								// header('Content-Type:text/html;charset=gbk');
								// echo '<pre>';
								//print_r($strs);
								
								//开始注入信息
								$data['name']=$strs[0];
								$data['mobile']=$strs[1];
								$data['sex']=$strs[2];
								$data['binzhong']=$strs[3];
								$data['status']=$strs[4];
								$data['beizhu']=$strs[5];
								$data['dateTime']=$data['dateTime']='20'.date("y-m-d",time());
								$data['doctorid']=$this->session->userdata('doctorId');
								$data['type']="批量导入";
								if($this->patient->addPatientOne($data)){
									  	//成功就什么都不做
									}else{
									  	//失败那么就记录一个
									  	//$error='';
									}	
						}

						$logData["operation"]="医生在后台导入了".$count."条患者";
						$logData["timeb"]='20'.date("y-m-d",time());
						$logData["person"]=$this->session->userdata('doctorName');
						$this->logAll->addOne($logData);

						$a=base_url("assets/error/psccg.html");
						header("Location: $a"); 
				  		exit();
					}else{
					    $a=base_url("assets/error/pscsb.html");
					    header("Location: $a"); 
	  					exit();
					}
	  		}else{
	  				//echo '<script>alert("文件格式不对")</script>';
	  				$a=base_url("assets/error/pwjerror.html");
	  				header("Location: $a"); 
	  				exit();
	  		}
	}


	//注销
	public function out(){
		$this->session->unset_userdata('doctorSession');
		$this->session->unset_userdata('doctorId');
		$this->session->sess_destroy();
		redirect('doctor/Login');
	}



	//删除一条记录
	public function deleteOne()
	{
		//设置验证规则
		$this->form_validation->set_rules('DoctorId','参数','required');
		 //先验证规则
		if($this->form_validation->run()==false){
			echo validation_errors();
			exit();
		}
		$data['id']=$this->input->post('DoctorId',TRUE);
		if($this->patient->deleteDoctorOne($data['id']))
		{

			$logData["operation"]="医生在后台删除了一个患者，患者ID是".$data['id'];
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('doctorName');
			$this->logAll->addOne($logData);
			echo 1;
		}else{
			echo 0;
		}

	}

	//添加一个患者
	public function addOnePatient(){
		$data['mobile']=$this->input->post('mobile',TRUE);
		$data['name']=$this->input->post('realName',TRUE);
		if($this->input->post('sex',TRUE)==1){
			$data['sex']="男";
		}else{
			$data['sex']="女";
		}

		$data['beizhu']=$this->input->post('beizhu',TRUE);
		
		$binzhong=$this->input->post('bingzhong',TRUE);
		

		if(strlen($binzhong)==0)
		{
			$data['binzhong']="";
		}else{
			$data['binzhong']=substr($binzhong,0,strlen($binzhong)-1);
		}

		$status=$this->input->post('status',TRUE);
		if(strlen($status)==0)
		{
			$data['status']="";
		}else{
			$data['status']=substr($status,0,strlen($status)-1);
		}

		$data['dateTime']='20'.date("y-m-d",time());
		$data['doctorid']=$this->session->userdata('doctorId');
		$data['type']="单条添加";

		//首先验证手机号码是否存在
		//单条添加，必须判断
		if($this->patient->cheAdminByNP($data['mobile'])){
			echo "2";
			exit();
		}

		//如果没有问题，开始添加
		if($this->patient->addPatientOne($data))
		{
			$logData["operation"]="医生在后台添加了一个患者，患者名称是".$data['name'];
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('doctorName');
			$this->logAll->addOne($logData);
			echo 1;
		}else{
			echo 0;
		}
	}


	public function searchMobile(){
		$name=$this->input->get('info',TRUE);
		$doctorid=$this->session->userdata('doctorId');
		 //获取所有信息
	    $data['dataDoctor']=$this->patient->getAll5($doctorid,$name);
	    $this->testexcel($data['dataDoctor']);
		$this->load->view("admin/Patient.html",$data);
		
	}

	public function searchMobile2(){
		$name=$this->input->get('info',TRUE);
		$doctorid=$this->session->userdata('doctorId');
		 //获取所有信息
	    $data['dataDoctor']=$this->patient->getAll3($doctorid,$name);
	    $this->testexcel($data['dataDoctor']);
		$this->load->view("admin/Patient.html",$data);
		
	}


	public function editorOne($id=1){
		$data['DoctorOne']=$this->patient->getPatientOne($id);
		$checkbz=array(
			'gxy'=>"",
			'tnb'=>"",
			'other'=>"",
			'otherValue'=>""
			);
		$gxy="";
		$tnb="";
		$other="";
		$otherValue="";

		$yjd="";
		$yqy="";
		$ysf="";
		$others="";
		$othersValue="";

		$binhzong=explode(',',$data['DoctorOne']['binzhong']);

		if(!empty($data['DoctorOne']['binzhong']))
		{
				foreach ($binhzong as $v) {
					if($v=="高血压"){
						$gxy="checked='checked'";
					}else if($v=="糖尿病"){
						$tnb="checked='checked'";
					}else{
						$other="checked='checked'";
						$otherValue=$v;
					}
				}
		}

		$status=explode(',',$data['DoctorOne']['status']);
		if(!empty($data['DoctorOne']['status']))
		{
			foreach ($status as $v) {
				if($v=="已建档"){
					$yjd="checked='checked'";
				}else if($v=="已签约"){
					$yqy="checked='checked'";
				}else if($v=="已随访"){
					$ysf="checked='checked'";
				}else{
					$others="checked='checked'";
					$othersValue=$v;
				}
			}
		}



		$aa="<div class='checkbox'><label><input name='checkbox1' $gxy id='gxyid' type='checkbox' class='ace' /><span class='lbl'> 高血压</span></label><label><input name='checkbox1' $tnb id='tnbid' type='checkbox' class='ace' /><span class='lbl'> 糖尿病</span></label><label><input name='checkbox1' id='qtid' $other type='checkbox' class='ace' /><span class='lbl'> 其它(请输入)：</span><input id='qtbzid' type='text' value='$otherValue' placeholder='添加其它病种'></label></div>";

		$bb="<div class='checkbox'><label><input name='checkbox2' $yjd id='yjdid' type='checkbox' class='ace' /><span class='lbl'> 已建档</span></label><label><input name='checkbox2' $yqy id='yqyid' type='checkbox' class='ace' /><span class='lbl'> 已签约</span></label><label><input name='checkbox2' id='ysfid' $ysf type='checkbox' class='ace' /><span class='lbl'> 已随访</span></label><label><input name='checkbox2' id='yqtid' $others type='checkbox' class='ace' /><span class='lbl'> 其他</span><input id='qtztid' type='text' value='$othersValue' placeholder='添加其它'></label></div>";																

		$data['binzhong']=$aa;
		$data['status']=$bb;
		$data['patientId']=$id;
		//print_r($data['binzhong']);
		//exit();
		$this->load->view("admin/PatientEditor.html",$data);
	}

	public function updatePatient(){

		$data['mobile']=$this->input->post('mobile',TRUE);
		$data['name']=$this->input->post('realName',TRUE);
		$data['sex']=$this->input->post('sex',TRUE);
		$data['beizhu']=$this->input->post('beizhu',TRUE);
		$binzhong=$this->input->post('bingzhong',TRUE);

		if(strlen($binzhong)==0)
		{
			$data['binzhong']="";
		}else{
			$data['binzhong']=substr($binzhong,0,strlen($binzhong)-1);
		}
		

		$status=$this->input->post('status',TRUE);
		if(strlen($status)==0)
		{
				$data['status']="";
		}else{
			$data['status']=substr($status,0,strlen($status)-1);
		}
		
		$id=$this->input->post('patientId',TRUE);
		//print_r($data);
		//exit();
		if($this->patient->updateOne($id,$data)){

			$logData["operation"]="医生在后台修改了一个患者，患者名称是".$data['name'];
			$logData["timeb"]='20'.date("y-m-d",time());
			$logData["person"]=$this->session->userdata('doctorName');
			$this->logAll->addOne($logData);
			echo '修改成功';
		}
		else {
			echo '修改错误，请联系开发员查看问题';
		}
	}

	public function testexcel($data){
		require "assets/PHPExcel/PHPExcel.php";
		$excel = new PHPExcel();
		$letter = array('A','B','C','D','E','F','G');
		$tableheader = array('姓名','手机号','性别','病种','状态','创建时间','类型');
		for($i = 0;$i < count($tableheader);$i++) {
			$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
		}

		foreach ($data as $k => $v) {
			$i=$k+2;
			$excel->getActiveSheet()->setCellValue("$letter[0]$i",$v['name']);
			$excel->getActiveSheet()->setCellValue("$letter[1]$i",$v['mobile']);
			$excel->getActiveSheet()->setCellValue("$letter[2]$i",$v['sex']);
			$excel->getActiveSheet()->setCellValue("$letter[3]$i",$v['binzhong']);
			$excel->getActiveSheet()->setCellValue("$letter[4]$i",$v['status']);
			$excel->getActiveSheet()->setCellValue("$letter[5]$i",$v['dateTime']);
			$excel->getActiveSheet()->setCellValue("$letter[6]$i",$v['type']);
		}

			$write = new PHPExcel_Writer_Excel5($excel);

			// header("Pragma: public");

			// header("Expires: 0");

			// header("Cache-Control:must-revalidate, post-check=0, pre-check=0");

			// header("Content-Type:application/force-download");

			// header("Content-Type:application/vnd.ms-execl");

			// header("Content-Type:application/octet-stream");

			// header("Content-Type:application/download");;

			// header('Content-Disposition:attachment;filename="testdata.xls"');

			// header("Content-Transfer-Encoding:binary");
			$filePath='/data/home/qxu2062660155/htdocs/1/assets/upload/'.$this->session->userdata('doctorName').'_patient.xls';
			$write->save($filePath);
	}

}